﻿using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class EnemySystem : Singleton<EnemySystem>
{
    [field: SerializeField] public EnemyBoardView enemyBoardView { get; set; }
    public List<Enemy> Enemies { get; private set; } = new List<Enemy>();

    void OnEnable()
    {
        ActionSystem.SubscribeReaction<EnemyTurnGA>(OnEnemyTurnPostReaction, ReactionTiming.POST);
        ActionSystem.AttachPerformer<KillEnemyGA>(KillEnemyPerformer);
    }

    void OnDisable()
    {
        ActionSystem.UnsubscribeReaction<EnemyTurnGA>(OnEnemyTurnPostReaction, ReactionTiming.POST);
        ActionSystem.DetachPerformer<KillEnemyGA>();
    }

    public void Setup(List<Enemy> enemyDatas)
    {
        foreach (var enemyData in enemyDatas)
        {
            enemyBoardView.AddEnemy(enemyData);
        }
    }
    public int id;
    public void SetupById(int id)
    {
        this.id = id;
        List<Enemy> enemyDatas = MapSystem.Instance.enemyDict[id];
        Setup(enemyDatas);
    }
    private void OnEnemyTurnPostReaction(EnemyTurnGA action)
    {
        StartCoroutine(EnemyTurnRoutine());
        HeroTurnStartGA heroTurnStartGA = new();
        ActionSystem.Instance.Perform(heroTurnStartGA);
    }
private IEnumerator EnemyTurnRoutine()
{
    // 生成 EnemyViews 副本，遍历副本不会受到列表修改影响
    var enemyViewsCopy = enemyBoardView.EnemyViews.ToArray();

    foreach (var enemyView in enemyViewsCopy)
    {
        if (enemyView == null) 
            continue; // 已经被移除的敌人跳过

        var purposeSystem = enemyView.GetComponent<PurposeSystem>();
        if (purposeSystem != null)
        {
            yield return purposeSystem.PerformCurrentPurpose();
        }
    }
}
    private IEnumerator KillEnemyPerformer(KillEnemyGA killEnemyGA)
    {
        yield return enemyBoardView.RemoveEnemy(killEnemyGA.EnemyView);
    }


}
